﻿#include "filemessage.h"

FileMessage::FileMessage(QWidget *parent)
    : BaseMessage{parent}
{
    setDefaultOption();
}
void FileMessage::setDefaultOption(){
    this->setWordWrapMode(QTextOption::WrapAnywhere);
    this->setReadOnly(true);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}

void FileMessage::setImage(QTextImageFormat &imageFormat){//设置图片
    QTextCursor cursor = this->textCursor();
    cursor.insertImage(imageFormat);
    if (!imageFormat.name().isEmpty()) {//获取图片的大小
        int lineWidth=imageFormat.width()+10;
        int lineHeight=imageFormat.height()+10;
        QWidget* oneWidget=this->parentWidget();
        oneWidget->setFixedHeight(lineHeight);//设置content_WT的高度
        QWidget* twoWidget=oneWidget->parentWidget();
        int differ=twoWidget->minimumHeight()-40;
        QWidget* fourWidget=twoWidget->parentWidget()->parentWidget();
        //设置限制最小宽度为217
        if(lineWidth>217+10)
            this->setFixedWidth(217+10);
        else
            this->setFixedWidth(lineWidth);
        //设置限制最大高度为217
        if(lineHeight>217+10)
            fourWidget->setFixedHeight(40+217+10+differ);
        else
            fourWidget->setFixedHeight(40+lineHeight+differ);
    }
}
void FileMessage::setImage(const QString &filePath){
    QSize targetSize=scaleImageSize(filePath);
    if(!targetSize.isNull()){
        QTextImageFormat imageFormat;
        imageFormat.setName(filePath);
        imageFormat.setWidth(targetSize.width());
        imageFormat.setHeight(targetSize.height());
        setImage(imageFormat);
    }
}

QSize FileMessage::scaleImageSize(const QString &imagePath){//缩放图片到适合的大小
    QPixmap pixmap(imagePath);
    if (pixmap.isNull()) {
        return QSize(0,0);
    }
    //按比例缩放图片
    //Qt::KeepAspectRatio保持长宽比
    //Qt::FastTransformation快速转换，提高处理速度，不考虑质量
    pixmap = pixmap.scaled(217, 217, Qt::KeepAspectRatio, Qt::FastTransformation);
    //设置最小的显示图片宽度为68
    if(pixmap.width()<68){
        pixmap=pixmap.scaledToWidth(68,Qt::FastTransformation);
    }
    //设置最小的显示图片高度为68
    if(pixmap.height()<68){
        pixmap=pixmap.scaledToHeight(68, Qt::FastTransformation);
    }
    return pixmap.size();
}

